package com.kanche.bigbaby.collection;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kanche.bigbaby.BigBabyApplication;
import com.kanche.bigbaby.R;
import com.kanche.bigbaby.AppConfig;
import com.kanche.bigbaby.collection.dialog.VehiclePhotoSelectionDialog;
import com.kanche.bigbaby.collection.domain.Gallery;
import com.kanche.bigbaby.collection.domain.Merchant;
import com.kanche.bigbaby.collection.domain.Photo;
import com.kanche.bigbaby.collection.domain.Vehicle;
import com.squareup.otto.Bus;
import com.squareup.otto.Subscribe;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import retrofit.RetrofitError;
/**
 * Created by nealmi on 6/10/14.
 */
public class VehicleEditorStep1Activity extends BaseActivity
        implements AdapterView.OnItemClickListener
        , VehiclePhotoSelectionDialog.OnChoiceMadeListener {

    private static final int CROP_IMAGE = 3;

    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
    private static final int SELECT_IMAGE_ACTIVITY_REQUEST_CODE = 101;
    private static final int SELECT_IMAGE_MULTIPLE_ACTIVITY_REQUEST_CODE = 102;
    private static final int EDIT_IMAGE_ACTIVITY_REQUEST_CODE = 103;
    private static final String TAG = "VehicleEditorStep1";
    /**
     * Create a File for saving an image or video
     */
    private static final int STEP2 = 200;
    private VehiclePhotosEditorAdapter adapter;
    private GridView container;
    private Photo current;
    private Uri capturedPhotoUri;
    private VehiclePhotoSelectionDialog photoSelectionDialog;
    private KKCheDBHelper dbHelper;
    private long rowId = -1;
    private Vehicle vehicle;
    private Bus bus;
    private ImageUploadTaskQueue queue;
    private List<Photo> toBeUploadedPhotos = new ArrayList<Photo>();
    private ProgressDialog progressDialog;
    private Gallery toBeUpdatedGallery;
    private List<Photo> uploadedPhotos = new ArrayList<Photo>();
    private Uri targetUri;
    private View contentWrapper, upload_hint;
    private DataSetObserver dataSetObserver = new DataSetObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            tips.setText("已经上传" + (adapter.getCount() - 1) + "/" + AppConfig.MAX_PHOTOS + "张照片");
            if (adapter.getCount() > 1) {
                upload_hint.setVisibility(View.GONE);
            }
        }
    };
    private TextView tips;
    private List<Photo> photos;
    private boolean isClose = false;

    //    private String merchantId = "";
    private Merchant merchant;

    Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.vehicle_editor_step1);
        toolbar = justFindIt(R.id.toolbar);
        toolbar.setTitle("采集图片");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        dbHelper = new KKCheDBHelper(this);
        if (null != getIntent()) {
//            this.merchantId = getIntent().getStringExtra("merchantId");
            this.merchant = (Merchant) (getIntent().getSerializableExtra("merchant"));
            rowId = getIntent().getLongExtra("rowId", rowId);
            vehicle = (Vehicle) getIntent().getSerializableExtra("vehicle");
        }

        bus = ((BigBabyApplication) getApplication()).getBus();

        tips = (TextView) findViewById(R.id.tips);
//        tips.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(getApplicationContext(), TaskPhotoEsotericaActivity.class);
//                startActivity(intent);
//            }
//        });
        contentWrapper = findViewById(R.id.contentWrapper);
        upload_hint = findViewById(R.id.tv_upload_hint);
        container = (GridView) findViewById(R.id.photos_editor);

        populateData();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_vehicle_step1,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:{
                back();
                break;
            }
            case R.id.next:{

                Gallery gallery = new Gallery();
                List<Photo> allPhotos = adapter.getData();
                gallery.setPhotos(allPhotos);

                if (gallery.getAllAvailablePhotos().size() < 1) {
                    Toast.makeText(VehicleEditorStep1Activity.this, "请至少添加1张车辆照片", Toast.LENGTH_LONG).show();
                    return true;
                }
                if (allPhotos.size() > 0)
                    allPhotos.remove(0);

                //
//                Vehicle vehicle = dbHelper.findVehicleByRowId(rowId);
//                if (vehicle == null) {
                if (-1 == rowId) {
                    vehicle = new Vehicle();
                    vehicle.setGallery(gallery);

                    vehicle.setMerchantId(BigBabyApplication.loadAccount(getApplicationContext()).getUser().getMerchant().getId());
                    vehicle.setMerchantUserId(BigBabyApplication.loadAccount(getApplicationContext()).getUser().getMerchant().getId());

                    rowId = dbHelper.insertVehicle(vehicle);


                    Vehicle svehicle = dbHelper.findVehicleByRowId(rowId);
                    vehicle.set_id(rowId);
                } else {
                    //If modify online vehicle
                    if (vehicle.getStatus().isDraft() && StringUtils.hasText(vehicle.getId())) {
                        gallery.setId(vehicle.getGalleryId());
                        startUpdateGallery(gallery);
                        return true;
                    } else {
                        vehicle.setGallery(gallery);
                        dbHelper.updateVehicle(rowId, vehicle);
                    }
                }
                nextStep();
            }
                break;
            }

        return super.onOptionsItemSelected(item);
    }

    private void populateData() {

        if (vehicle != null && vehicle.getGallery() != null && photos == null) {
            photos = vehicle.getGallery().getPhotos();
        }
        if (photos == null) {
            photos = new ArrayList<Photo>();
        }
        if ((photos.size() == 0 || (photos.size() > 0 && !photos.get(0).getKey().equalsIgnoreCase("add_photo")))) {
            photos.add(0, new Photo("add_photo", ""));
        }

        adapter = new VehiclePhotosEditorAdapter(photos, this);
        adapter.registerDataSetObserver(dataSetObserver);
        container.setOnItemClickListener(this);
        container.setAdapter(adapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        bus.register(this);
        populateData();
        if (null != photoSelectionDialog)
            photoSelectionDialog.dismiss();
    }

    @Override
    protected void onPause() {
        super.onPause();
        bus.unregister(this);
    }

    @Override
    public void onMediaStoreSelected() {

        photoSelectionDialog.dismiss();
        openGalleryChooser();
    }

    private void openGalleryChooser() {
        List<Photo> photos = adapter.getData();
        ArrayList<CharSequence> selectedPaths = new ArrayList<CharSequence>();

        for (Photo photo : photos) {
            String original = photo.getOriginal();
            if (StringUtils.hasText(original))
                selectedPaths.add(original);
        }

        Intent intent = new Intent(this, GalleryChooserActivity.class);
        intent.putExtra("limitation", AppConfig.MAX_PHOTOS - (adapter.getCount() - 1));
        intent.putCharSequenceArrayListExtra("selectedPaths", selectedPaths);
        startActivityForResult(intent, SELECT_IMAGE_MULTIPLE_ACTIVITY_REQUEST_CODE);
    }

    @Override
    public void onSetCover(Photo photo) {
        photoSelectionDialog.dismiss();
        adapter.moveToFirst(photo);
        adapter.commit();
    }

    @Override
    public void onEditImage(Photo photo) {
//        Intent intent = new Intent();
//        intent.setClass(getApplicationContext(), DrawPhotoActivity.class);
//        intent.putExtra(DrawPhotoActivity.PHOTO, photo);
//        startActivityForResult(intent, EDIT_IMAGE_ACTIVITY_REQUEST_CODE);
    }

    @Override
    public void onCameraSelected() {
        photoSelectionDialog.dismiss();

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        capturedPhotoUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
        intent.putExtra(MediaStore.EXTRA_OUTPUT, capturedPhotoUri); // set the image file name

        // start the image capture Intent
        startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
    }

    public boolean cropCapturedImage(Uri sourceUri, Uri targetUri) {
        return false;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == STEP2 && resultCode == RESULT_OK) {
            setResult(RESULT_OK, data);
            finish();
        }
        try {
            if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        if (data.getExtras() != null) {
                            Bitmap bitmap = (Bitmap) data.getExtras().get("data");
                            if (bitmap != null) {
                                Log.i(TAG, "Save thumbnail from camera app!");
                                ImageUtils.saveImageAsJPGE(bitmap, capturedPhotoUri.getPath(), 60);
                            }
                        }
                        if (StringUtils.hasText(data.getDataString())) {
                            capturedPhotoUri = Uri.parse(data.getDataString());
                        }
                    }

                    File targetFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
                    targetUri = Uri.fromFile(targetFile);

                    if (!cropCapturedImage(capturedPhotoUri, targetUri)) {
                        String source = capturedPhotoUri.getPath();
                        String target = targetFile.getPath();

                        if (ImageUtils.cropImage(source, target, getBSSApplication().imageWidth()
                                , getBSSApplication().imageHeight(), false)) {
                            adapter.add(target, source);
                            adapter.commit();
                        } else {
                            Toast.makeText(this, "图片处理错误!", Toast.LENGTH_LONG).show();
                        }
                    }

                } else if (resultCode == RESULT_CANCELED) {
                    // User cancelled the image capture
                } else {
                    // Image capture failed, advise user
                }
            }
            if (requestCode == CROP_IMAGE && RESULT_OK == resultCode) {
                if (targetUri != null)
                    adapter.update(current.getKey(), targetUri.getPath());
            }

            if (requestCode == SELECT_IMAGE_ACTIVITY_REQUEST_CODE) {
                if (resultCode == RESULT_OK) {
                    Uri fullPhotoUri = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(fullPhotoUri,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String source = cursor.getString(columnIndex);
                    String target = getOutputMediaFile(MEDIA_TYPE_IMAGE).getPath();
                    if (ImageUtils.cropImage(source, target, getBSSApplication().imageWidth()
                            , getBSSApplication().imageHeight(), false)) {
                        adapter.update(current.getKey(), target);
                    } else {
                        Toast.makeText(this, "图片处理错误!", Toast.LENGTH_LONG).show();
                    }
                    cursor.close();

                } else if (resultCode == RESULT_CANCELED) {
                    // User cancelled the image capture
                } else {
                    // Image capture failed, advise user
                }
            }

            if (requestCode == SELECT_IMAGE_MULTIPLE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
                final ArrayList<CharSequence> paths = data.getCharSequenceArrayListExtra("paths");
                final ProgressDialog progress = new ProgressDialog(VehicleEditorStep1Activity.this, ProgressDialog.STYLE_SPINNER);
                progress.setMessage("图片处理中");
                progress.show();

                new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected void onPreExecute() {
                        super.onPreExecute();
                    }

                    @Override
                    protected Void doInBackground(Void... params) {


                        int len = paths.size();
                        for (int i = 0; i < len; i++) {
                            String target = getOutputMediaFile(MEDIA_TYPE_IMAGE).getPath();

                            CharSequence source = paths.get(i);
//                            progress.setMessage("图片处理中" + (i + 1) + "/" + len);
                            if (ImageUtils.cropImage(String.valueOf(source), target
                                    , getBSSApplication().imageWidth(), getBSSApplication().imageHeight(), false)) {
                                adapter.add(target, String.valueOf(source));
                            }
                        }


                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        super.onPostExecute(aVoid);
                        if (!isClose) {
                            progress.dismiss();
                        }
                        adapter.commit();
                    }
                }.execute();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

//        if (requestCode == EDIT_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == DrawPhotoActivity.EDIT_IMAGE_RESULT_OK) {
//            photoSelectionDialog.dismiss();
//            Photo photo = (Photo) data.getSerializableExtra("photo");
//            adapter.update(photo.getKey(), photo.getUri());
//        }
    }

    private void dismissProgressDialog() {
        if (progressDialog != null)
            progressDialog.dismiss();
    }

    private void setProgressMessage(String message) {
        if (progressDialog != null)
            progressDialog.setMessage(message);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        current = (Photo) adapterView.getItemAtPosition(i);
        if ("add_photo".equalsIgnoreCase(current.getKey()) && (adapter.getCount() - 1) >= 24) {
            Guard.showMessage(this, "图片数量已达上线");
            return;
        }
        if ("add_photo".equalsIgnoreCase(current.getKey())) {
            openGalleryChooser();
            return;
        }
//        openSelection();
    }

    private void openSelection() {
        if (photoSelectionDialog == null) {
            photoSelectionDialog = new VehiclePhotoSelectionDialog();
            photoSelectionDialog.setListener(this);
            photoSelectionDialog.setCancelable(true);
            photoSelectionDialog.setShowsDialog(true);
        }
        photoSelectionDialog.setPhoto(current);
        photoSelectionDialog.show(getSupportFragmentManager(), "photoSelectionDialog");
    }

    @Override
    protected void onDestroy() {
        isClose = true;
//        dbHelper.close();
        adapter.unregisterDataSetObserver(dataSetObserver);
        super.onDestroy();
    }

    private void back() {
        setResult(RESULT_CANCELED);
        finish();    //finish当前activity
        overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_bottom);
    }

    private void nextStep() {

        BigBabyApplication.NeedRefresh_CollectionFrag = true;

        Intent intent = new Intent(this, VehicleEditorStep2Activity.class);
        intent.putExtra("rowId", rowId);
        startActivityForResult(intent, STEP2);
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onDelete(Photo photo) {
        photoSelectionDialog.dismiss();
        adapter.remove(photo);
        adapter.commit();
//        try {
//            new File(photo.getUri()).delete();
//        } catch (Exception e) {
//
//        }
    }

    private void startUpdateGallery(Gallery gallery) {
        uploadPhotos(gallery);
    }

    //    //Step 1: upload photos
    private void uploadPhotos(Gallery gallery) {
        if (queue == null) {
            queue = ImageUploadTaskQueue.create(this, new Gson(), bus);
            BigBabyApplication application = ((BigBabyApplication) getApplication());
            application.setQueue(queue);
        }
        List<Photo> ps = gallery.getPhotos();
        gallery.setPhotos(new ArrayList<Photo>());

        toBeUpdatedGallery = new Gallery();
        toBeUpdatedGallery.setId(gallery.getId());


        if (toBeUploadedPhotos == null) {
            toBeUploadedPhotos = new ArrayList<Photo>();
        } else {
            toBeUploadedPhotos.clear();
        }

        List<Photo> deletedOrUnchangedPhotos = new ArrayList<Photo>();
        long batchId = vehicle.get_id();
        for (Photo photo : ps) {
            String uri = photo.getUri();
            if (StringUtils.hasText(uri) && !StringUtils.isHttpPath(uri)) {
                queue.add(new ImageUploadTask(photo, batchId, getContext()));
                toBeUploadedPhotos.add(photo);
            } else {
                deletedOrUnchangedPhotos.add(photo);
            }
        }

        toBeUpdatedGallery.setPhotos(deletedOrUnchangedPhotos);
        if (toBeUploadedPhotos.size() == 0) {
            uploadedPhotos.clear();
            progressDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);

            progressDialog.setMessage("上传中。。");
            progressDialog.show();
            updateGallery(toBeUpdatedGallery);
//            nextStep();
        } else {
            progressDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);

            progressDialog.setMessage("上传图片:" + "0/" + toBeUploadedPhotos.size());
            progressDialog.show();
        }
    }

    //
//    //Step 2: create gallery
    private void updateGallery(Gallery gallery) {
//        progressDialog.setMessage("Updating gallery");

        getBSSService().updateGallery(gallery, new retrofit.Callback<Gallery>() {
            @Override
            public void success(Gallery galleryResult, retrofit.client.Response response) {
                dismissProgressDialog();
                uploadedPhotos.clear();
                toBeUpdatedGallery = null;
                nextStep();
            }

            @Override
            public void failure(RetrofitError error) {
                dismissProgressDialog();
                uploadedPhotos.clear();
                Guard.handleError(VehicleEditorStep1Activity.this, error);
            }
        });
    }

    //
    @Subscribe
    public void onQueueSizeChanged(ImageUploadQueueSizeEvent event) {
    }

    @SuppressWarnings("UnusedDeclaration") // Used by event bus.
    @Subscribe
    public void onUploadSuccess(ImageUploadSuccessEvent event) {
        if (event.batchId != vehicle.get_id()) {
            return;
        }
        if (uploadedPhotos == null) {
            uploadedPhotos = new ArrayList<Photo>();
        }

        uploadedPhotos.add(event.photo);
        setProgressMessage(getString(R.string.uploading_photos) + uploadedPhotos.size() + "/" + toBeUploadedPhotos.size());


        if (uploadedPhotos.size() == toBeUploadedPhotos.size()) {
            toBeUpdatedGallery.getPhotos().addAll(uploadedPhotos);
            updateGallery(toBeUpdatedGallery);
        }
    }

    @SuppressWarnings("UnusedDeclaration") // Used by event bus.
    @Subscribe
    public void onUploadFailure(ImageUploadFailureEvent event) {
        if (event.batchId != vehicle.get_id()) {
            return;
        }
        dismissProgressDialog();
        Guard.handleError(this, event.error);
        if (uploadedPhotos != null)
            uploadedPhotos.clear();
        if (toBeUploadedPhotos != null)
            toBeUploadedPhotos.clear();

    }

    protected Context getContext() {
        return this;
    }

}
